/**
 *
 * Created by hugohoo on 10/17/16.
 */

$(document).ready(function(){
    $("#addModalTrigger").on('click', function(){
        $('#addModal').openModal();
    });

    $("#addModalSubmit").on('click', function(){
        let Message = {
            message : $("#message").val(),
            author : $("#author").val()
        };
        console.log(Message);

        asynchronizedMessage(Message);
    });

});

function asynchronizedMessage(Message){
    let xhr = new XMLHttpRequest();

    xhr.open("post", "../messageboard/add.action", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("info=" + JSON.stringify(Message));
    xhr.onreadystatechange = function(){
        if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
            console.log(JSON.parse(xhr.responseText));

            addNewMessage(JSON.parse(xhr.responseText));
            clearModal();
        }
    }
}

function addNewMessage(Message){
    let $table = $("#messageTable");
    let tableRowLen = $table.get(0).rows.length;
    let newRow = $table.get(0).insertRow(tableRowLen);

    newRow.insertCell(0).innerText = Message.id;
    newRow.insertCell(1).innerText = Message.message;
    newRow.insertCell(2).innerText = Message.author;
    newRow.insertCell(3).innerText = Message.time;
}

function clearModal(){
    $("#message").val("");
    $("#author").val("");
}